package com.jml.zlhq.app.ui;

import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.ui.WebAppInterface.webCallBack;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.FoundWebView;
import com.jml.zlhq.app.widgets.FoundWebView.ScrollInterface;

@SuppressWarnings("deprecation")
public class ShopDetailActivity extends BaseActivity {
	private FoundWebView webView;
	private LinearLayout loadpage;
	private TextView loadText;
	private int topPicH;
	private RelativeLayout header;
	private String url;
	private String id;
	private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
                if(msg.what!=200) {//主页不存在  
                    //载入本地assets文件夹下面的错误提示页面404.html  
                	loadText.setText("很抱歉，出错啦！"); 
                } else {  
                	Log.i("==web url==", url);
                	webView.loadUrl(url);  
                	
                }  
        }  
	};
	public webCallBack share,collect,info;
	@SuppressWarnings("unused")
	private String infoStr;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shop_detail_activity);
		
		topPicH = (int) (UIUtil.winWidth*320/640-getResources().getDimension(R.dimen.header_hight));;
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setImageResource(R.drawable.share_selector);
		ImageView roghtImage2 = (ImageView) findViewById(R.id.content_header_right_img2);
		roghtImage2.setVisibility(View.GONE);
		roghtImage2.setImageResource(R.drawable.collect_selector);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setVisibility(View.INVISIBLE);
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		loadpage = (LinearLayout)findViewById(R.id.load_info_lay);
		loadText = (TextView) findViewById(R.id.load_info);
		loadpage.setVisibility(View.VISIBLE);
		
		roghtImage1.setOnClickListener(this);
		roghtImage2.setOnClickListener(this);
		
		header = (RelativeLayout) findViewById(R.id.content_header);
		header.setBackgroundColor(getResources().getColor(R.color.black));
		header.getBackground().setAlpha(0);
		
		ImageView spaceshipImage = new ImageView(this);
		spaceshipImage.setImageResource(R.drawable.publicloading);
		Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.loading_animation);
		loadpage.addView(spaceshipImage, 0);
		spaceshipImage.startAnimation(hyperspaceJumpAnimation);
		
		webView = (FoundWebView) findViewById(R.id.shop_detail_web);
		
		this.initWebView();
		
		webView.setOnCustomScroolChangeListener(new ScrollInterface() {
			@Override
			public void onSChanged(int l, int t, int oldl, int oldt) {
				int alpha = t*255/topPicH;
				alpha = alpha>220?220:alpha;
				alpha = alpha<0?0:alpha;
				header.getBackground().setAlpha(alpha);
			}
		});
		
		//if()
		//if(crowdUrl!=null&&crowdUrl.contains("/map"))crowdUrl = "http://192.168.1.254:8080/"+crowdUrl.substring(crowdUrl.indexOf("/map"));
		try {
			url = getIntent().getExtras().getString("url");
			if(appContext.isLogin())url = url+"&auth_token="+appContext.getLoginUid();
			id = getIntent().getExtras().getString("id");
		} catch (Exception e) {
			e.printStackTrace();
		}
		new Thread(new Runnable() {  
            @Override  
            public void run() {  
                    Message msg = new Message();  
                    //此处判断主页是否存在，因为主页是通过loadUrl加载的，  
                    //此时不会执行shouldOverrideUrlLoading进行页面是否存在的判断  
                    //进入主页后，点主页里面的链接，链接到其他页面就一定会执行shouldOverrideUrlLoading方法了  
                    msg.what = getRespStatus(url);  
                    handler.sendMessage(msg);  
            }  
		}).start(); 
		share = new webCallBack() {
			@Override
			public void call(Object str) {
				UIUtil.showLoadingDialog(ShopDetailActivity.this, "加载中，请稍后...", false);
				appContext.showShare(URLs.SHARE_SHOWSHOP+"?id="+id);
			}
		};
		info = new webCallBack() {
			
			@Override
			public void call(Object obj) {
				infoStr = obj!=null?obj.toString():null;
			}
		};
		// 用JavaScript调用Android函数：
		// 先建立桥梁类，将要调用的Android代码写入桥梁类的public函数
		// 绑定桥梁类和WebView中运行的JavaScript代码
		// 将一个对象起一个别名传入，在JS代码中用这个别名代替这个对象，可以调用这个对象的一些方法
		webView.addJavascriptInterface(new WebAppInterface(this,share,collect,info), "appInterface");
	}

	@Override
	public void loadData(Map<String, String> param) {}

	@Override
	public void clearData() {}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==1&&appContext.isLogin()){
			url = url+"&auth_token="+appContext.getLoginUid();
			Log.i("==web url==", url);
		}
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView(){
		// 得到设置属性的对象
		WebSettings webSettings = webView.getSettings();
		// 使能JavaScript
		webSettings.setJavaScriptEnabled(true);
		// 支持中文，否则页面中中文显示乱码
		webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setSaveFormData(false);  
        webSettings.setSupportZoom(false);  
        webSettings.setBlockNetworkImage(true);
		clearCach(webView);
		// 限制在WebView中打开网页，而不用默认浏览器
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
		webView.setWebViewClient(new WebViewClient(){
			 @Override  
		     public boolean shouldOverrideUrlLoading(WebView view, String url) {  
				 return true;  
			 }  
		});
		// 如果不设置这个，JS代码中的按钮会显示，但是按下去却不弹出对话框
		// Sets the chrome handler. This is an implementation of WebChromeClient
		// for use in handling JavaScript dialogs, favicons, titles, and the
		// progress. This will replace the current handler.
		webView.setWebChromeClient(new EXWebChromeClient());
	}

	protected void clearCach(WebView webView) {
		webView.clearCache(true); 
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieManager.getInstance().removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		CookieSyncManager.getInstance().startSync();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.content_header_right_img:
			if(share!=null)share.call(null);
			//UIUtil.showLoadingDialog(this, "加载中，请稍后...", false);
			//appContext.showShare(URLs.SHARE_WORK+"?id="+id);
			break;
		default:
			break;
		}
	}
	
	/** 
     * 继承WebChromeClient类 
     * 对js弹出框时间进行处理 
     *  
     */  
    private class EXWebChromeClient extends WebChromeClient {  
  
        /** 
         * 处理alert弹出框 
         */  
        @Override  
        public boolean onJsAlert(WebView view,String url, String message, JsResult result) {  
//            mReusultText.setText("Alert:"+message);  
//            //对alert的简单封装  
//            new AlertDialog.Builder(WebViewDemo.this).  
//                setTitle("Alert").setMessage(message).setPositiveButton("OK",  
//                new DialogInterface.OnClickListener() {  
//                    @Override  
//                    public void onClick(DialogInterface arg0, int arg1) {  
//                       //TODO  
//                   }  
//            }).create().show();  
//            result.confirm();  
            return super.onJsAlert(view, url, message, result);  
        }  
  
        /** 
         * 处理confirm弹出框 
         */  
        @Override  
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {  
//            mReusultText.setText("Confirm:"+message);  
//            result.confirm();  
            return super.onJsConfirm(view, url, message, result);  
        }  
  
        /** 
         * 处理prompt弹出框 
         */  
        @Override  
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {  
//            mReusultText.setText("Prompt input is :"+message);  
//            result.confirm();  
            return super.onJsPrompt(view, url, message, message, result);  
        }  
        
        public void onProgressChanged(WebView view,int newProgress){
        	loadText.setText("玩命加载中\t"+newProgress+"%");
        	if(newProgress>=100){
        		header.getBackground().setAlpha(0);
        		loadpage.setVisibility(View.GONE);
        		webView.getSettings().setBlockNetworkImage(false);
        	}
        }
    }  
	
	/**
	 * 自定义的Android代码和JavaScript代码之间的桥梁类
	 * 
	 * @author 1
	 * 
	 */
//	public class WebAppInterface {
//		Context mContext;
//
//		/** Instantiate the interface and set the context */
//		WebAppInterface(Context c) {
//			mContext = c;
//		}
//
//		/** Show a toast from the web page */
//		// 如果target 大于等于API 17，则需要加上如下注解window.thirdLogin.login(param)
//		@JavascriptInterface
//		public void method(String type,String id) {
//			Log.i("====js====", type+","+id);
//		}
//	}

	private int getRespStatus(String url) {  
        int status = -1;  
        try {  
                HttpHead head = new HttpHead(url);  
                HttpClient client = new DefaultHttpClient();  
                HttpResponse resp = client.execute(head);  
                status = resp.getStatusLine().getStatusCode();  
        } catch (Exception e) {}  
        return status;  
	} 
}
